/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <linux/stddef.h>
void tj_string_trim_left(char string[]) {
	char* pos = string;
	while (*pos == ' ' || *pos == '\t' || *pos == '\n' || *pos == '\r') {
		*pos++;
	}
	strcpy(string, pos);
}

void tj_string_trim_right(char string[]) {
	int pos = strlen(string) - 1;
	while ((string[pos] == ' ' || string[pos] == '\t' || string[pos] == '\n' || string[pos] == '\r') && pos >= 0) {
		pos--;
	};
	string[pos + 1] = '\0';
}

void tj_string_trim(char string[]) {
	tj_string_trim_left(string);
	tj_string_trim_right(string);
}
void tj_string_substr(char *str, int start_position, int const length, char result[]) {
	int end_position = start_position + length;
	int i = 0;
	while (start_position <= end_position) {
		result[i] = str[start_position];
		if (str[start_position] == '\0') {
			break;
		}
		start_position++;
		i++;
	}
	result[length] = '\0';
}

int tj_string_index(char string[], char sub_string[]) { //strstr
	if (strlen(string) < strlen(sub_string)) {
		return -1;
	}
	int result = 0;
	while (string[result] != '\0') {
		int i = 0;
		int same_length = 0;
		while (sub_string[i] != '\0') {
			if (sub_string[i] == string[result + same_length]) {//result + same_length 是为了知道第一个相同开始的索引位置
				same_length++;
				if (same_length == strlen(sub_string)) {
					return result;
				}
			}
			i++;
		}
		result++;
	}
	return -1;
}

int tj_string_replace(char* string, char* src, char* des) {
	char backup[256];
	if (string != NULL) {
		strcpy(backup, string);
	} else {
		printf("str_replace err!\n");
		return -1;
	}
	char buffer[256];
	memset(buffer, 0x00, sizeof(buffer));

	char* pos = NULL;
	int index = 0;
	while ((pos = strstr(backup, src)) != 0) {
		if (pos - backup != 0) {
			memcpy(&buffer[index], backup, pos - backup);
		}
		memcpy(&buffer[index + pos - backup], des, strlen(des));
		index += pos - backup + strlen(des);
		strcpy(backup, pos + strlen(src));
	}
	strcat(buffer, backup);
	strcpy(string, buffer);
	return 0;
}
